/*
 * Copyright 2009-2012 Prime Teknoloji.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.jm.mala.view;

import br.jm.mala.dao.ModulosDao;
import br.jm.mala.entity.Modulos;
import br.jm.mala.entity.Roles;
import br.jm.mala.entity.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.primefaces.context.RequestContext;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("menuView")
@Scope("view")
public class MenuView implements Serializable {

    private static final long serialVersionUID = -4465129548834119489L;

    public static MenuModel modelCadastro;
    public static MenuModel modelConsulta;
    public static MenuModel modelRelatorio;
    public static MenuModel modelAdministrativo;
    private final UserSession session;
    private final User user;
    private DefaultMenuItem item;
    private DefaultSubMenu Submenu;
    private List<Modulos> listModulos;
    private final ModulosDao modulosDao;
    public static boolean salvar = true;

    @Autowired
    public MenuView(UserSession session, ModulosDao modulosDao) {
        this.modulosDao = modulosDao;
        this.session = session;
        this.user = this.session.getUser();
        MenuView.salvar = true;
        String cSql;

        // MONTA MENU CADASTROS
        if (modelCadastro == null) {
            modelCadastro = new DefaultMenuModel();
            item = null;
            Submenu = null;

            if (user.getRoles().get(0).getDescription().equals("ROLE_ADMIN")) {
                cSql = "select modulo_id,description,dsc_modulo,num_nivel,ordem, menu "
                        + "from modulos "
                        + "where menu = 'cad' "
                        + "order by num_nivel, ordem";
                listModulos = (List<Modulos>) modulosDao.getNativeFiltroList(cSql);
            } else {
                listModulos = user.getRoles().get(0).getRolesModulosList();
                List sortFields = new ArrayList();
                sortFields.add(new BeanComparator("numNivel"));
                sortFields.add(new BeanComparator("ordem"));

                ComparatorChain multiSort = new ComparatorChain(sortFields);

                java.util.Collections.sort(listModulos, multiSort);
            }
            // Monta o Menu do Usuario
            for (Modulos selectedModulos : listModulos) {
                switch (selectedModulos.getOrdem()) {
                    case "A":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        modelCadastro.addElement(item);
                        break;
                    case "B":
                        if (Submenu != null) {
                            modelCadastro.addElement(Submenu);
                        }
                        Submenu = new DefaultSubMenu(selectedModulos.getDscModulo());
                        break;
                    case "C":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        Submenu.addElement(item);
                        break;
                }
            }
            modelCadastro.addElement(Submenu);

            listModulos.stream().map((_item) -> {
                item = new DefaultMenuItem(" ");
                return _item;
            }).forEach((_item) -> {
                modelCadastro.addElement(item);
            });
        }
        // MONTA MENU CONSULTAS
        if (modelConsulta == null) {
            modelConsulta = new DefaultMenuModel();
            item = null;
            Submenu = null;

            if (user.getRoles().get(0).getDescription().equals("ROLE_ADMIN")) {
                cSql = "select modulo_id,description,dsc_modulo,num_nivel,ordem, menu "
                        + "from modulos "
                        + "where menu = 'con' "
                        + "order by num_nivel, ordem";
                listModulos = (List<Modulos>) modulosDao.getNativeFiltroList(cSql);
            } else {
                listModulos = user.getRoles().get(0).getRolesModulosList();
                List sortFields = new ArrayList();
                sortFields.add(new BeanComparator("numNivel"));
                sortFields.add(new BeanComparator("ordem"));

                ComparatorChain multiSort = new ComparatorChain(sortFields);

                java.util.Collections.sort(listModulos, multiSort);
            }
            // Monta o Menu do Usuario
            for (Modulos selectedModulos : listModulos) {
                switch (selectedModulos.getOrdem()) {
                    case "A":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        modelConsulta.addElement(item);
                        break;
                    case "B":
                        if (Submenu != null) {
                            modelConsulta.addElement(Submenu);
                        }
                        Submenu = new DefaultSubMenu(selectedModulos.getDscModulo());
                        break;
                    case "C":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        Submenu.addElement(item);
                        break;
                }
            }
            if (Submenu != null) {
                modelConsulta.addElement(Submenu);
            }

            listModulos.stream().map((_item) -> {
                item = new DefaultMenuItem(" ");
                return _item;
            }).forEach((_item) -> {
                modelConsulta.addElement(item);
            });
        }
        // MONTA MENU RELATORIOS
        if (modelRelatorio == null) {
            modelRelatorio = new DefaultMenuModel();
            item = null;
            Submenu = null;

            if (user.getRoles().get(0).getDescription().equals("ROLE_ADMIN")) {
                cSql = "select modulo_id,description,dsc_modulo,num_nivel,ordem, menu "
                        + "from modulos "
                        + "where menu = 'rel' "
                        + "order by num_nivel, ordem";
                listModulos = (List<Modulos>) modulosDao.getNativeFiltroList(cSql);
            } else {
                listModulos = user.getRoles().get(0).getRolesModulosList();
                List sortFields = new ArrayList();
                sortFields.add(new BeanComparator("numNivel"));
                sortFields.add(new BeanComparator("ordem"));

                ComparatorChain multiSort = new ComparatorChain(sortFields);

                java.util.Collections.sort(listModulos, multiSort);
            }
            // Monta o Menu do Usuario
            for (Modulos selectedModulos : listModulos) {
                switch (selectedModulos.getOrdem()) {
                    case "A":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        modelRelatorio.addElement(item);
                        break;
                    case "B":
                        if (Submenu != null) {
                            modelRelatorio.addElement(Submenu);
                        }
                        Submenu = new DefaultSubMenu(selectedModulos.getDscModulo());
                        break;
                    case "C":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        Submenu.addElement(item);
                        break;
                }
            }
            if (Submenu != null) {
                modelRelatorio.addElement(Submenu);
            }

            listModulos.stream().map((_item) -> {
                item = new DefaultMenuItem(" ");
                return _item;
            }).forEach((_item) -> {
                modelRelatorio.addElement(item);
            });
        }
        // MONTA MENU ADMINISTRATIVO
        if (modelAdministrativo == null) {
            modelAdministrativo = new DefaultMenuModel();
            item = null;
            Submenu = null;

            if (user.getRoles().get(0).getDescription().equals("ROLE_ADMIN")) {
                cSql = "select modulo_id,description,dsc_modulo,num_nivel,ordem, menu "
                        + "from modulos "
                        + "where menu = 'adm' "
                        + "order by num_nivel, ordem";
                listModulos = (List<Modulos>) modulosDao.getNativeFiltroList(cSql);
            } else {
                listModulos = user.getRoles().get(0).getRolesModulosList();
                List sortFields = new ArrayList();
                sortFields.add(new BeanComparator("numNivel"));
                sortFields.add(new BeanComparator("ordem"));

                ComparatorChain multiSort = new ComparatorChain(sortFields);

                java.util.Collections.sort(listModulos, multiSort);
            }
            // Monta o Menu do Usuario
            for (Modulos selectedModulos : listModulos) {
                switch (selectedModulos.getOrdem()) {
                    case "A":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        modelAdministrativo.addElement(item);
                        break;
                    case "B":
                        if (Submenu != null) {
                            modelAdministrativo.addElement(Submenu);
                        }
                        Submenu = new DefaultSubMenu(selectedModulos.getDscModulo());
                        break;
                    case "C":
                        item = new DefaultMenuItem(selectedModulos.getDscModulo());
                        item.setUrl(selectedModulos.getDescription());
                        item.setIcon("ui-icon-home");
                        Submenu.addElement(item);
                        break;
                }
            }
            modelAdministrativo.addElement(Submenu);

            int nItem = 5;
            if (listModulos.size() > 5) {
                nItem = listModulos.size();
            }
            for (int i = 0; i < nItem; i++) {
                item = new DefaultMenuItem(" ");

                modelAdministrativo.addElement(item);
            }

        }
    }

    @PostConstruct
    public void init() {
        if (!FacesContext.getCurrentInstance().isPostback()) {
            RequestContext.getCurrentInstance().execute("fechaPanel()");
        }
    }

    public MenuModel getModelCadastro() {
        return modelCadastro;
    }

    public MenuModel getModelConsulta() {
        return modelConsulta;
    }

    public MenuModel getModelRelatorio() {
        return modelRelatorio;
    }

    public MenuModel getModelAdministrativo() {
        return modelAdministrativo;
    }

    public boolean verificaAcesso(int nModulo) {
        return verificaAcesso(nModulo, null);
    }

    public void fechaDialog() {
        MenuView.salvar = true;
    }

    public boolean verificaAcesso(int nModulo, String cModulo) {
        boolean lReturn = false;

        if (cModulo == null) {
            cModulo = "menu";
        }

        if (salvar && cModulo.equals("alterar")) {
            return false;
        } else if (!salvar && cModulo.equals("incluir")) {
            return false;
        } else {
            for (int i = 0; i < user.getRoles().size(); i++) {
                Roles seletectedRole = user.getRoles().get(i);
                if (seletectedRole.getDescription().equals("ROLE_ADMIN")) {
                    lReturn = true;
                    break;
                } else {
                    if (nModulo == 0) {
                        lReturn = false;
                        break;
                    } else {
                        for (int j = 0; j < seletectedRole.getRolesModulosList().size(); j++) {
                            Modulos selectedModulo = seletectedRole.getRolesModulosList().get(j);
                            if (selectedModulo.getModuloId() == nModulo) {
                                if (cModulo.equals("menu")) {
                                    lReturn = true;
                                    break;
                                } else {
                                    switch (cModulo) {
                                        case "incluir":
                                            lReturn = !(selectedModulo.getIncluir() == null);
                                            break;
                                        case "alterar":
                                            lReturn = !(selectedModulo.getAlterar() == null);
                                            break;
                                        case "excluir":
                                            lReturn = !(selectedModulo.getExcluir() == null);
                                            break;
                                        case "consultar":
                                            lReturn = !(selectedModulo.getConsultar() == null);
                                            break;
                                    }
                                }
                            }
                        }
                        if (lReturn) {
                            break;
                        }
                    }
                }
            }
        }

        return lReturn;
    }

    public boolean isSalvar() {
        return salvar;
    }

    public void setSalvar(boolean salvar) {
        MenuView.salvar = salvar;
    }
}
